package com.byxy.dao.impl;

import com.byxy.dao.AdminGroupDao;
import com.byxy.model.AdminGroup;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class AdminGroupDaoImpl implements AdminGroupDao {
    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public void save(AdminGroup adminGroup) {
        if (adminGroup.getParent().getId() == null) {
            adminGroup.setParent(null);
        }
        sessionFactory.getCurrentSession().save(adminGroup);
    }

    @Override
    public void delete(Integer id) {
        AdminGroup adminGroup = (AdminGroup) sessionFactory.getCurrentSession().load(AdminGroup.class, id);
        sessionFactory.getCurrentSession().delete(adminGroup);
    }

    @Override
    public void update(AdminGroup adminGroup) {
        if (adminGroup.getParent().getId() == null) {
            adminGroup.setParent(null);
        }
        sessionFactory.getCurrentSession().update(adminGroup);
    }

    @Override
    public AdminGroup get(Integer id) {
        return (AdminGroup) sessionFactory.getCurrentSession().load(AdminGroup.class, id);
    }

    @Override
    public List<AdminGroup> listPage(Integer pageNum, Integer pageSize, String search) {
        //language=HQL
        String hql = "FROM AdminGroup WHERE title LIKE :search";
        Query query = sessionFactory.getCurrentSession().createQuery(hql);
        query.setParameter("search", "%".concat(search).concat("%"));
        if (pageNum > 0 && pageSize > 0) {
            query.setFirstResult((pageNum - 1) * pageSize);
            query.setMaxResults(pageSize);
        }
        return query.list();
    }

    @Override
    public Integer count(String search) {
        //language=HQL
        String hql = "SELECT COUNT(*) FROM AdminGroup WHERE title LIKE :search";
        return ((Long) sessionFactory.getCurrentSession().createQuery(hql)
                .setParameter("search", "%".concat(search).concat("%"))
                .uniqueResult())
                .intValue();
    }
}
